//
//  NoFinishOrderController.m
//  PersonnelWashCar
//
//  Created by 张越 on 16/4/27.
//  Copyright © 2016年 张越. All rights reserved.
//

#import "NoFinishOrderController.h"
#import "NoFinishOrderCell.h"
#import "NoFinishDetailController.h"
#import "LoginViewController.h"
#import "NOFinshModel.h"
#import "AffirmOrderController.h"

@interface NoFinishOrderController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>

@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic,assign)NSInteger page;
@property (strong, nonatomic) IBOutlet UIImageView *nothingImage;
@property (strong, nonatomic) IBOutlet UILabel *nothingLabel;

@end

@implementation NoFinishOrderController
- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        self.dataSource = [NSMutableArray new];
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   self.tableView.backgroundColor = [UIColor colorFromHexCode:@"f8f8f8"];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.page = 1;
    [self webRequest_GetOrderInfo];
    // 添加上拉刷新控件
    [self.tableView addFooterWithTarget:self action:@selector(loadMoreData)];
    
    // 添加下拉刷新控件
    [self.tableView addHeaderWithTarget:self action:@selector(loadOnePageData)];
    [self.tableView headerBeginRefreshing];
    self.tableView.tag = 101;
}

- (void)loadMoreData
{
    self.page++;
    [self webRequest_GetOrderInfo];
}

- (void)loadOnePageData
{
    self.page = 1;
    [self webRequest_GetOrderInfo];
}

#pragma mark -- 网络请求 --
-(void)webRequest_GetOrderInfo
{
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    hud.labelText = @"正在加载...";
    [self.view addSubview:hud];
//    [hud show:YES];
    __weak typeof(self)weakself = self;
    NSString *uidStr = [[NSUserDefaults standardUserDefaults] objectForKey:KUserDefaultsUserIdKey];
    NSString *page = [NSString stringWithFormat:@"%ld",self.page];
    NSDictionary *dict = @{@"uid":uidStr,@"typeid":@"1",@"page": page};
    [HttpRequestManager getMethod:KOrderListInterface parameters:dict completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (success) {
            if (self.page == 1) {
                [self.dataSource removeAllObjects];
            }
            self.dataSource = nil;
            NSMutableArray *ary = response[@"data"][@"orderlist"];
            for (NSMutableDictionary *dic in ary) {
                NOFinshModel *model = [MTLJSONAdapter modelOfClass:[NOFinshModel class] fromJSONDictionary:dic error:nil];
                [weakself.dataSource insertObject:model atIndex:0];
            }
            [weakself.tableView reloadData];
        }else{
            
        }
        [weakself.tableView footerEndRefreshing];
        [weakself.tableView headerEndRefreshing];
    }];
}

#pragma UITableViewDataSource And UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.dataSource.count > 0) {
        self.nothingImage.hidden = self.nothingLabel.hidden = YES;
    }else{
        self.nothingImage.hidden = self.nothingLabel.hidden = NO;
    }
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *cellIdentifier = @"NoFinishOrderCell";
    NoFinishOrderCell *cell= [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        [tableView registerNib:[UINib nibWithNibName:@"NoFinishOrderCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
        cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    }
    NOFinshModel *model = self.dataSource[indexPath.section];
    cell.noFinshModel = model;

    [cell.orderAffirmBtn addTarget:self action:@selector(orderAffirmButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    cell.orderAffirmBtn.tag = indexPath.section+1000;
    
    [cell.orderCancleBtn addTarget:self action:@selector(orderCancleBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    cell.orderCancleBtn.tag = indexPath.section+100;
    
    return cell;
}

- (void)orderAffirmButtonClicked:(UIButton *)sender
{
    NOFinshModel *model = self.dataSource[sender.tag - 1000];
    AffirmOrderController *affirmVC = [[AffirmOrderController alloc]init];
    affirmVC.hidesBottomBarWhenPushed = YES;
    affirmVC.orderSN = model.sn;
    [self.navigationController pushViewController:affirmVC animated:YES];
}

- (void)orderCancleBtnClicked:(UIButton *)sender
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"真的要取消订单吗？" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消",nil];
    [alert show];
    alert.tag = sender.tag;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NOFinshModel *model = self.dataSource[alertView.tag - 100];
        if(buttonIndex == 0)
        {
            NSDictionary *dict = [[NSDictionary alloc]init];
            dict = @{@"sn":model.sn};
            [HttpRequestManager postMethod:KCanaleOrderInterface parameters:dict completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
                if (success) {
                    [SVProgressHUD showSuccessWithStatus:@"订单取消成功"];
                    [self.dataSource removeAllObjects];
                    [self webRequest_GetOrderInfo];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"LoadTableView" object:nil];

                }else {
                    [SVProgressHUD showErrorWithStatus:@"订单取消失败"];
                }
            }];
        }
}

#pragma mark - UITableViewDelegate
-(nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * sectionView = [[UIView alloc]initWithFrame:CGRectMake(0,0, ScreenWidth, 12)];
    sectionView.backgroundColor = [UIColor clearColor];
    return sectionView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 172;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 12;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
    [tableView reloadData];
    NOFinshModel *model = self.dataSource[indexPath.section];
    NoFinishDetailController *orderVC = [[NoFinishDetailController alloc]init];
    orderVC.orderSN = model.sn;
    orderVC.hidesBottomBarWhenPushed = YES;
    orderVC.fromStr = @"待完成";
    [self.navigationController pushViewController:orderVC animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
